<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="code" label="合同编码">
          <InputTagDialog v-model="listQuery.code" placeholder="合同编码" title="填写合同编码" />
        </el-form-item>
        <el-form-item prop="name" label="合同名称">
          <el-input v-model="listQuery.name" placeholder="合同名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="type" label="合同类型">
          <ContractType v-model="listQuery.type" keyName="id" keyShow="name" placeholder="合同类型" title="合同类型查询" />
        </el-form-item>
        <el-form-item prop="contractSignerId" label="合同签订人">
          <ContractSigner v-model="listQuery.contractSignerId" keyName="id" keyShow="name" placeholder="合同签订人" title="合同签订人查询" />
        </el-form-item>
        <el-form-item prop="contractSignerDepartmentId" label="合同签订部门">
          <Organization v-model="listQuery.contractSignerDepartmentId" keyName="id" keyShow="organizationName" placeholder="签订部门" title="部门查询" />
        </el-form-item>
        <el-form-item prop="departmentId" label="负责部门">
          <Organization v-model="listQuery.departmentId" keyName="id" keyShow="organizationName" placeholder="负责部门" title="部门查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="userId" label="负责人用户">
          <User v-model="listQuery.userId" keyName="id" keyShow="name" placeholder="负责人用户" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <!--
        <el-form-item prop="amount" label="合同金额">
          <el-input v-model="listQuery.amount" placeholder="合同金额" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <ConditionSwitch>
          <template #condition>
            <el-form-item label="合同起始时间">
              <el-date-picker v-model="listQuery.contractLaunchRange"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              type="datetimerange"
                              range-separator="-"
                              start-placeholder="合同起始时间(从)"
                              end-placeholder="合同起始时间(到)" />
            </el-form-item>
            <el-form-item label="合同终止时间">
              <el-date-picker v-model="listQuery.contractCompleteRange"
                              value-format="YYYY-MM-DD HH:mm:ss"
                              type="datetimerange"
                              range-separator="-"
                              start-placeholder="合同终止时间(从)"
                              end-placeholder="合同终止时间(到)" />
            </el-form-item>
            <el-form-item prop="needInspection" label="是否需要验收">
              <el-radio-group v-model="listQuery.needInspection">
                <el-radio-button label="" key="">全部</el-radio-button>
                <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <!--
            <el-form-item prop="contractTemplateId" label="合同模版ID">
              <el-input v-model="listQuery.contractTemplateId" placeholder="合同模版ID" @keyup.enter="handleFilter" />
            </el-form-item>
            -->
            <el-form-item prop="state" label="合同状态">
              <el-radio-group v-model="listQuery.state">
                <el-radio-button label="" key="">全部</el-radio-button>
                <el-radio-button v-for="(item,index) in getEnumList('ContractInitialState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </template>
        </ConditionSwitch>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="合同编码" prop="code" min-width="150px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.code" /></template>
      </el-table-column>
      <el-table-column align="center" label="合同名称" prop="name" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="合同类型" prop="type" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(contractTypeList, row.type, 'name') }}</template>
      </el-table-column>
      <el-table-column align="center" label="合同金额" prop="amount" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><MoneyTag :money="row.amount" /></template>
      </el-table-column>
      <el-table-column align="center" label="合同起始时间" prop="contractLaunch" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.contractLaunch?.substring(0,10) }}</template>
      </el-table-column>
      <el-table-column align="center" label="合同终止时间" prop="contractComplete" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.contractComplete?.substring(0,10) }}</template>
      </el-table-column>
      <el-table-column align="center" label="需要验收" prop="needInspection" min-width="100px" show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonYesNo')" :enum-key="row.needInspection" />
        </template>
      </el-table-column>
      <!--
      <el-table-column align="center" label="合同模版ID" prop="contractTemplateId" min-width="155px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="合同内容" prop="content" min-width="200px" show-overflow-tooltip>
        <template v-slot="{row}"><span style="display: inline-block; width: 200px; white-space: nowrap;overflow: hidden;text-overflow: ellipsis;" v-html="row.content"></span></template>
      </el-table-column>
      -->
      <el-table-column align="center" label="合同状态" prop="state" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('ContractInitialState')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同签订人" prop="contractSignerId" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ getIdLabel(contractSignerList, row.contractSignerId, 'name') }}</template>
      </el-table-column>
      <el-table-column align="center" label="合同签订部门" prop="contractSignerDepartmentId" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreignIds="row.contractSignerDepartmentId" :foreignLabel="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="负责部门" prop="departmentId" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="organizationList" :foreign-ids="row.departmentId" :foreign-label="'organizationName'" /></template>
      </el-table-column>
      <el-table-column align="center" label="负责人用户" prop="userId" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreign-ids="row.userId" :foreign-label="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="220px">
        <template v-slot="{row}">
          <div class="" style="display: flex; align-items: center;">
            <el-button type="success" link @click="handleView(row)">查看</el-button>
            <el-button type="success" link @click="handlePreview(row)">预览</el-button>
            <el-dropdown trigger="click" :hide-on-click="false">
              <span class="el-dropdown-link">操作<el-icon class="el-icon--right"><arrow-down /></el-icon></span>
              <template #dropdown>
                <el-button v-show="checkAuthByCode('')"
                           type="primary" link @click="handleEdit(row)"
                           v-if="checkAuthByCode('') && ['0','3','4'].includes(row.state)">编辑</el-button>
                <el-dropdown-item v-if="checkAuthByCode('') && ['0','3','4'].includes(row.state)">
                  <el-popconfirm confirm-button-text="确定"
                                 cancel-button-text="取消"
                                 :icon="WarningFilled"
                                 icon-color="#626AEF"
                                 title="您确定删除么？"
                                 @confirm="handleDelete(row)">
                    <template #reference>
                      <el-button type="danger" link>删除</el-button>
                    </template>
                  </el-popconfirm>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['1'].includes(row.state)">
                  <el-popconfirm confirm-button-text="确定"
                                 cancel-button-text="取消"
                                 :icon="InfoFilled"
                                 icon-color="#626AEF"
                                 title="您确定撤回么？"
                                 @confirm="handleRevocation(row)">
                    <template #reference>
                      <el-button type="danger" link>撤回</el-button>
                    </template>
                  </el-popconfirm>
                </el-dropdown-item>
                <!--主线状态编辑-->
                <el-dropdown-item v-if="checkAuthByCode('') && ['2'].includes(row.state)">
                  <el-button type="primary" link @click="visibleBtn2(row.id)" style="padding: 5px 0" >生效</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6'].includes(row.state) && row.catalog !== '3'">
                  <el-button type="primary" link @click="handleOperation(row, 3, 13)" style="padding: 5px 0">请款</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="((checkAuthByCode('') && ['7'].includes(row.state)) || (checkAuthByCode('') && ['5'].includes(row.state) && row.catalog === '3')) && row.needInspection === '1'">
                  <el-button type="primary" link @click="handleOperation(row, 1, 7)" style="padding: 5px 0">验收</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="(checkAuthByCode('') && ['9'].includes(row.state)) || ((checkAuthByCode('') && ['5'].includes(row.state) && row.catalog === '3') && row.needInspection === '0') || (checkAuthByCode('') && ['7'].includes(row.state) && row.needInspection === '0')">
                  <el-button type="primary" link @click="visibleBtn3(row.id, row.contractComplete, row.needInspection, row.catalog)" style="padding: 5px 0">完结</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['10'].includes(row.state)">
                  <el-button type="primary" link @click="visibleBtn4(row.id, row.contractComplete, row.needInspection, row.catalog)" style="padding: 5px 0">合同归档</el-button>
                </el-dropdown-item>
                <!--支线状态编辑-->
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1 , 5)" style="padding: 5px 0">补充协议</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1, 12)" style="padding: 5px 0">变更</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1, 6)" style="padding: 5px 0">转交</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1, 9)" style="padding: 5px 0">登记纠纷</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1, 8)" style="padding: 5px 0">授权</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1, 15)" style="padding: 5px 0">跟踪</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state) && (!row.isInterrupt || row.isInterrupt === '0')">
                  <el-button type="primary" link @click="handleOperation(row, 1, 10)" style="padding: 5px 0">中止</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && row.isInterrupt === '1'">
                  <el-button type="primary" link @click="visibleBtn1(row.id)" style="padding: 5px 0">重启合同</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1 ,11)" style="padding: 5px 0">终止</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5','6', '7', '8', '9', '10', '11'].includes(row.state)">
                  <el-button type="primary" link @click="handleOperation(row, 1 ,14)" style="padding: 5px 0">合同借阅</el-button>
                </el-dropdown-item>
              </template>
            </el-dropdown>
            <el-dropdown trigger="click" :hide-on-click="false">
              <span class="el-dropdown-link">详情<el-icon class="el-icon--right"><arrow-down /></el-icon></span>
              <template #dropdown>
                <el-dropdown-item v-if="checkAuthByCode('') && ['1','2','3','4','5','6', '7', '8', '9', '10', '11'].includes(row.state)">
                  <el-button type="success" link @click="handleApprove(row)">审批流程</el-button>
                </el-dropdown-item>
                <!--状态详情-->
                <el-dropdown-item v-if="checkAuthByCode('') && ['8', '9', '10', '11'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2, 7)" style="padding: 5px 0">验收详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2, 10)" style="padding: 5px 0">中止详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2 , 5)" style="padding: 5px 0">补充协议详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9', '10', '11'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2 , 14)" style="padding: 5px 0">借阅记录</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2 , 12)" style="padding: 5px 0">变更详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2 , 15)" style="padding: 5px 0">跟踪详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2, 6)" style="padding: 5px 0">转交详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2, 9)" style="padding: 5px 0">合同纠纷详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2, 8)" style="padding: 5px 0">授权详情</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-if="checkAuthByCode('') && ['5', '6', '7', '8', '9'].includes(row.state)">
                  <el-button type="success" link @click="handleOperation(row, 2 ,11)" style="padding: 5px 0">终止详情</el-button>
                </el-dropdown-item>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogApproveVisible" title="审批流程" width="55%" top="2vh">
      <approveTimeline :businessType="approveOrderBusinessTypes().contractMain" :businessId="obj.id" />
      <div style="text-align:right;margin: 1.875rem 0;">
        <el-button type="danger" @click="dialogApproveVisible=false">关闭</el-button>
      </div>
    </el-dialog>
    <!--合同生效-->
    <el-dialog v-model="takeEffectVisible" title="上传已生效合同" width="70%" top="2vh">
      <el-form class="my-form" ref="approveIdObj" :model="obj" label-position="right" label-width="auto">
        <el-form-item label="上传已盖章合同附件" prop="budgetName">
          <FileUpload :isShowTip="false" v-model="oFile1" :isShowFileList="true" :isDrag="true" @uploadedSuccess="uploadedSuccessFn" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="takeEffectVisible=false">关闭</el-button>
        <el-button type="primary" @click="effectContractSubmit">确定</el-button>
      </div>
    </el-dialog>
    <!--重启合同-->
    <el-dialog v-model="restartVisible" title="合同归档地址" width="50%" align-center>
      <div class="visible">是否重启合同？</div>
      <div style="text-align:right;">
        <el-button type="danger" @click="restartVisible=false">关闭</el-button>
        <el-button type="primary" @click="restartSubmit">确定</el-button>
      </div>
    </el-dialog>
    <!--合同完结-->
    <el-dialog v-model="endVisible" title="合同完结" width="50%" align-center>
      <div class="visible1" v-if="catalog === '1' || catalog === '2'">
        <el-icon color="#67C23A" :size="22"><SuccessFilled /></el-icon>
        <span>合同已全部请款</span>
      </div>
      <div class="visible1" v-if="needInspection === '1'">
        <el-icon color="#67C23A" :size="22"><SuccessFilled /></el-icon>
        <span>合同已全部验收</span>
      </div>
      <div class="visible1">
        <el-icon :color="isEnd ? '#67C23A' : '#F56C6C'" :size="22">
          <SuccessFilled v-if="isEnd" />
          <CircleCloseFilled v-else />
        </el-icon>
        <span>合同已过截止日期</span>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="endVisible=false">关闭</el-button>
        <el-button type="primary" @click="completeSubmit" :disabled="!isEnd">确认完结</el-button>
      </div>
    </el-dialog>
    <!--合同归档-->
    <el-dialog v-model="gVisible" title="合同归档" width="50%" align-center>
      <el-form class="my-form" ref="approveIdObj" :model="obj" label-position="right" label-width="auto">
        <el-form-item label="合同归档地址" prop="budgetName">
          <el-input v-model="address" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" class="textarea-1" />
        </el-form-item>
      </el-form>
      <div class="visible1" v-if="catalog === '1' || catalog === '2'">
        <el-icon color="#67C23A" :size="22"><SuccessFilled /></el-icon>
        <span>合同已全部请款</span>
      </div>
      <div class="visible1" v-if="needInspection === '1'">
        <el-icon color="#67C23A" :size="22"><SuccessFilled /></el-icon>
        <span>合同已全部验收</span>
      </div>
      <div class="visible1">
        <el-icon :color="isEnd ? '#67C23A' : '#F56C6C'" :size="22">
          <SuccessFilled v-if="isEnd" />
          <CircleCloseFilled v-else />
        </el-icon>
        <span>合同已过截止日期</span>
      </div>
      <div class="visible1">
        <el-icon color="#67C23A" :size="22"><SuccessFilled /></el-icon>
        <span>合同已完结</span>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="gVisible=false">关闭</el-button>
        <el-button type="primary" @click="fileSubmit" :disabled="!isEnd">确认归档</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doDelete, doGet, doGetDownload, doPost} from '@/config/http'
import approveTimeline from '@/views/components/base/approveTimeline.vue'
import {approveOrderBusinessTypes, customValidator, getListPageSize, notifySuccess} from '@/config/common'
import InputTagDialog from '@/components/InputTag/inputTagDialog.vue';
import SvgIcon from '@/components/SvgIcon/index.vue';
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import ConditionSwitch from "@/components/ConditionSwitch/index.vue";
import ContractSigner from "@/views/components/contract/selectContractSigner.vue";
import ContractType from "@/views/components/contract/selectContractType.vue";
import {getUserId} from "@/config/cookie";
import useUserStore from "@/store/modules/user";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  kind: '2', // 合同种类，1初始合同，2主合同
  code: null, // 合同编码
  name: null, // 合同名称
  type: null, // 合同类型
  contractSignerId: null, // 合同签订人ID
  contractSignerDepartmentId: null, // 合同签订部门ID
  departmentId: null, // 负责部门ID
  userId: null, // 负责人用户ID
  amount: null, // 合同金额
  contractLaunch: null, // 合同起始时间
  contractComplete: null, // 合同终止时间
  needInspection: null, // 是否需要验收
  contractTemplateId: null, // 合同模版ID
  content: null, // 合同内容
  state: null, // 合同状态
  isInterrupt: null, // 是否中止
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'contractMain_nocache',
  components: {
    ContractSigner,
    ContractType,
    Organization,
    User,
    ConditionSwitch,
    SvgIcon,
    InputTagDialog,
    approveTimeline
  },
  mixins: [baseConfig],
  data() {
    const svc = 'icims-api'
    return {
      svc,
      obj: Object.assign({}, emptyObj),
      routes: [],
      nameOfPermission: null,
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        kind: '2',
        code: null,
        name: null,
        type: null,
        contractSignerId: null,
        contractSignerDepartmentId: null,
        departmentId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
        userId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        amount: null,
        contractLaunchStart: null,
        contractLaunchEnd: null,
        contractLaunchRange: [],//
        contractCompleteStart: null,
        contractCompleteEnd: null,
        contractCompleteRange: [],//
        needInspection: null,
        contractTemplateId: null,
        state: null,
        isInterrupt: null, // 是否中止
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        code: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同编码', trigger: ['blur', 'change'] }],
        name: [{ required: true, validator: customValidator, min: 1, max: 200, label: '合同名称', trigger: ['blur', 'change'] }],
        type: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同类型', trigger: ['blur', 'change'] }],
        contractSignerId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同签订人ID', trigger: ['blur', 'change'] }],
        contractSignerDepartmentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同签订部门ID', trigger: ['blur', 'change'] }],
        departmentId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '负责部门ID', trigger: ['blur', 'change'] }],
        userId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '负责人用户ID', trigger: ['blur', 'change'] }],
        amount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '合同金额', trigger: ['blur', 'change'] }],
        contractLaunch: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同起始时间', trigger: ['blur', 'change'] }],
        contractComplete: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同终止时间', trigger: ['blur', 'change'] }],
        needInspection: [{ required: false, validator: customValidator, min: 0, max: 20, label: '是否需要验收', trigger: ['blur', 'change'] }],
        contractTemplateId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同模版ID', trigger: ['blur', 'change'] }],
        content: [{ required: false, validator: customValidator, min: 0, max: 0, label: '合同内容', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同状态', trigger: ['blur', 'change'] }],
      },
      dialogApproveVisible: false,
      governmentList: initListStore().governmentList,
      organizationList: initListStore().organizationList,
      userList: initListStore().userList,
      contractTypeList: initListStore().contractTypeList,
      contractSignerList: initListStore().contractSignerList,
      oFiles: [],
      oFile1: [],
      takeEffectVisible: false,
      fileAdVisible: false,
      restartVisible: false,
      endVisible: false,
      gVisible: false,
      rowId: '',
      address: '',
      isEnd: false, // 是否到完结时间
      needInspection: '', // 是否需要验收
      catalog: '', // 是否需要请款
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  async created() {
    this.nameOfPermission = 'contractMain'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    // await this.initList()
    await this.getList()
  },
  methods: {
    useUserStore,
    approveOrderBusinessTypes,
    // async initList() {
    //   let p1 = doGet(this.svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(this.svc, '/contract-type/page', {pageSize: getListPageSize()}, false)
    //   let p5 = doGet(this.svc, '/contract-signer/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4, p5])
    //   this.governmentList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.userList = resArray[2]['records']
    //   this.contractTypeList = resArray[3]['records']
    //   this.contractSignerList = resArray[4]['records']
    // },
    async getList() {
      this.listLoading = true
      this.listQuery.contractLaunchStart = ''
      this.listQuery.contractLaunchEnd = ''
      if (this.listQuery.contractLaunchRange) {
        this.listQuery.contractLaunchStart = this.listQuery.contractLaunchRange[0]
        this.listQuery.contractLaunchEnd = this.listQuery.contractLaunchRange[1]
      }
      this.listQuery.contractCompleteStart = ''
      this.listQuery.contractCompleteEnd = ''
      if (this.listQuery.contractCompleteRange) {
        this.listQuery.contractCompleteStart = this.listQuery.contractCompleteRange[0]
        this.listQuery.contractCompleteEnd = this.listQuery.contractCompleteRange[1]
      }
      doGet(this.svc, '/contract-initial/page', this.listQuery).then(async res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
        this.list = this.list.map(item => {
          let index = this.contractTypeList.findIndex(item1 => item1.id === item.type)
          item.catalog = this.contractTypeList[index]?.catalog
          return item
        })
        console.debug('this.list',this.list)
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleApprove(row) {
      this.obj = Object.assign({}, row)
      this.dialogApproveVisible = true
    },
    handleResetQuery() {
      this.resetForm("listQuery")
      this.listQuery.contractLaunchStart = ''
      this.listQuery.contractLaunchEnd = ''
      this.listQuery.contractLaunchRange = []
      this.listQuery.contractCompleteStart = ''
      this.listQuery.contractCompleteEnd = ''
      this.listQuery.contractCompleteRange = []
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row, type) {
      if (type && type === 'change') {
        // 合同变更
        this.goTargetByName('contractMainEdit', {id: row.id, oper: 'change'})
      } else {
        // 合同编辑
        this.goTargetByName('contractMainEdit', {id: row.id, oper: 'edit'})
      }
    },
    handleView(row) {
      this.goTargetByName('contractMainEdit', {id: row.id, oper: 'view'})
    },
    handleAdd() {
      this.goTargetByName('contractMainEdit', {oper: 'add'})
    },
    handlePreview(row) {
      // view:合同预览， edit：合同状态编辑， stateView， 合同状态预览，state：合同状态
      this.goTargetByName('contractInitialOperation', {id: row.id, oper: 'view', kind: '2'})
    },
    handleOperation(row, type, state) {
      // row.state
      if (type === 1) {
        // 编辑模式
        this.goTargetByName('contractInitialOperation', {id: row.id, oper: 'edit', kind: '2', state: state})
      } else if (type === 2) {
        // 查看模式
        this.goTargetByName('contractInitialOperation', {id: row.id, oper: 'view', kind: '2', state: state})
      } else {
        // 编辑模式 請款
        this.goTargetByName('contractInitialOperation', {id: row.id, oper: 'edit', kind: '2', state: state, catalog: row.catalog})
      }
    },
    handleExport() {
      doGetDownload(this.svc, '/contract-initial/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, `/contract-initial/${row.id}`, {}).then(() => {
        notifySuccess('删除成功')
        this.getList()
        this.dialogVisible = false
      })
    },
    handleRevocation(row) {
      doPost(this.svc, `/customContractInitial/revocationContractInitial/${row.id}`, {}, true).then(() => {
        notifySuccess('撤回成功')
        this.getList()
      })
    },
    takeEffectFn() {
      this.takeEffectVisible = true
    },
    visibleBtn1(id) {
      this.rowId = id
      this.restartVisible = true
    },
    visibleBtn2(id) {
      this.rowId = id
      this.takeEffectVisible = true
    },
    visibleBtn3(id, endTime, needInspection, catalog) {
      this.rowId = id
      this.needInspection = needInspection
      this.catalog = catalog
      let completeDate = Date.parse(new Date(endTime))
      let newDate = Date.parse(new Date())
      this.isEnd = completeDate <= newDate
      this.endVisible = true
    },
    visibleBtn4(id, endTime, needInspection, catalog) {
      this.rowId = id
      this.needInspection = needInspection
      this.catalog = catalog
      let completeDate = Date.parse(new Date(endTime))
      let newDate = Date.parse(new Date())
      this.isEnd = completeDate <= newDate
      this.gVisible = true
    },
    visibleBtn5(id) {
      this.rowId = id
      this.fileAdVisible = true
    },
    uploadedSuccessFn(file) {
      console.debug('file---------------',file)
      let filesObj = {
        attachmentId: file.attachmentId ? file.attachmentId : file.id, // 附件ID
        attachmentName: file.file ? file.file.name : file.fileName, // 附件名称
        attachmentType: '', // 附件类型
        attachmentUrl: file.url ? file.url : '',	//附件URL		false
        attachmentSize: file.size ? file.size : file.fileSize, //附件大小
        attachmentUpload: file.createTime, //附件上传时间
        attachmentUploader: file.updateBy, //附件上传人
        contractInitialId: this.rowId, // 合同ID
        createBy: '', // 创建人用户ID
        createTime: '', // 创建时间
        id: '', // 主键ID
        updateBy: '', // 最后修改人用户ID
        updateTime: '', // 最后修改时间
        version: '', // 数据版本
      }
      this.oFile1.push(filesObj)
      console.debug('this.oFile1',this.oFile1)
    },
    //合同生效
    effectContractSubmit() {
      let items = this.oFile1.map(item => {
        item.effectUserId = getUserId()
        item.effectDepartmentId = useUserStore().organization.id
        return item
      })
      let o = {}
      o.oper = 'add'
      o.approveId = null
      o.approveNodes = []
      o.items = items
      doPost(this.svc, `/customContractInitial/effectContractInitial/${this.rowId}`, o, true).then(() => {
        notifySuccess('操作成功')
        this.takeEffectVisible = false
        this.getList()
      })
    },
    // 重启合同
    restartSubmit() {
      let items = [{
        contractInitialId: this.rowId,
        restartUserId: getUserId(),
        restartDepartmentId: useUserStore().organization.id,
      }]
      let o = {}
      o.oper = 'add'
      o.approveId = null
      o.approveNodes = []
      o.items = items
      doPost(this.svc, `/customContractInitial/restartContractInitial/${this.rowId}`, o, true).then(() => {
        notifySuccess('操作成功')
        this.restartVisible = false
        this.getList()
      })
    },
    // 合同完结
    completeSubmit() {
      let items = [{
        contractInitialId: this.rowId,
        completeUserId: getUserId(),
        completeDepartmentId: useUserStore().organization.id,
      }]
      let o = {}
      o.oper = 'add'
      o.approveId = null
      o.approveNodes = []
      o.items = items
      doPost(this.svc, `/customContractInitial/completeContractInitial/${this.rowId}`, o, true).then(() => {
        notifySuccess('操作成功')
        this.endVisible = false
        this.getList()
      })
    },
    //  合同归档
    fileSubmit() {
      let items = [{
        contractInitialId: this.rowId,
        archivePosition: this.address,
        archiveUserId: getUserId(),
        archiveDepartmentId: useUserStore().organization.id,
      }]
      let o = {}
      o.oper = 'add'
      o.approveId = null
      o.approveNodes = []
      o.items = items
      doPost(this.svc, `/customContractInitial/archiveContractInitial/${this.rowId}`, o, true).then(() => {
        notifySuccess('操作成功')
        this.gVisible = false
        this.getList()
      })
    }
  }
}
</script>
<style scoped>
.visible {
  font-size: 22px;
  color: #303133;
  font-weight: bold;
  text-align: center;
}
.visible1 {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
}
.visible1 span {
  padding-left: 10px;
  font-size: 22px;
  color: #303133;
  font-weight: bold;
  text-align: center;
}
.el-dropdown-link {
  font-size: 14px;
}
</style>
